package com.logansoft.servicehomework.controller;

import com.logansoft.servicehomework.entity.CommonResult;
import com.logansoft.servicehomework.entity.User;
import com.logansoft.servicehomework.mapper.UserMapper;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author liqiye
 * @description 测试持久层
 * @date 2021/7/16
 */

@RestController
@RequestMapping("/mybatisplus")
public class TestMybatisPlusController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/testList")
    public CommonResult testList() {
        // 参数Wrapper，条件构造器
        List<User> userList = userMapper.selectList(null);
        return new CommonResult(200, "成功", userList);
    }

    @GetMapping("/testInsert")
    public CommonResult testInsert(){
        User user = new User();
        user.setName("张三");
        user.setAge(23);
        int i= userMapper.insert(user);  // 没有id的默认自动使用雪花算法
        System.out.println(i);
        return new CommonResult(200, "成功");
    }

    @GetMapping("/testUpdate")
    public CommonResult testUpdate(){
        User user = new User();
        user.setId(6L);
        user.setName("李启业");
        user.setAge(24);
        int i = userMapper.updateById(user);
        System.out.println(i);
        return new CommonResult(200, "成功");
    }

    // 测试乐观锁成功
    @GetMapping("/testOptimisticLock")
    public CommonResult testOptimisticLock(){
        User user = userMapper.selectById(6L);
        user.setName("李启业仔");
        // 如果属性的version没有值，他就不会自动用乐观锁判断
        // User user1 = new User();
        // user1.setId(6L);
        // user1.setName("李启业");
        userMapper.updateById(user);
        return new CommonResult(200, "成功");
    }

    // 测试乐观锁失败
    @GetMapping("/testOptimisticLockE")
    public CommonResult testOptimisticLockE(){
        // 模拟线程1
        User user = userMapper.selectById(6L);
        user.setName("李启业仔");

        // 模拟线程2
        User user2 = userMapper.selectById(6L);
        user2.setName("李启业仔2");

        userMapper.updateById(user2);  // 先执行

        userMapper.updateById(user);
        return new CommonResult(200, "成功");
    }


}
